package com.ruoyi.traplight.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.Threads;
import com.ruoyi.permission.Dao.SerDevicePermi;
import com.ruoyi.permission.domain.DevicePermiInsectInfo;
import com.ruoyi.permission.mapper.SerDevicePermiMapper;
import com.ruoyi.traplight.domain.PhotoDao;
import com.ruoyi.traplight.domain.TraplightDetectionLog;
import com.ruoyi.traplight.domain.SelectPhotoDao;
import com.ruoyi.traplight.mapper.TrapLightDataMapper;
import com.ruoyi.traplight.mapper.TrapLightDeviceMapper;
import com.ruoyi.traplight.service.ModelService;
import com.ruoyi.traplight.service.PhotoService;
import com.ruoyi.utils.ImgDrawCircleTool;
import com.ruoyi.utils.ParseString;
import com.ruoyi.utils.RpcRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;

/**
 * @author FLInt
 * @date 2021/10/20 11:56
 */
@Service
@Slf4j
public class PhotoServiceImpl implements PhotoService {

//    @Autowired
//    private AliyunClientService aliyunClientService;

    @Autowired
    private TrapLightDeviceMapper deviceMapper;

    @Autowired
    private TrapLightDataMapper dataMapper;

    @Autowired
    private ModelService modelService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SerDevicePermiMapper permiMapper;

    @Value("${ruoyi.profile}")
    private String profile;

    /**
     * 模型检测图像处理路径
     */
    @Value("${ruoyi.detectionUrl}")
    private String detectionUrl;

    /**
     * 获取设备物联网实例、密钥
     *
     * @param deviceName 设备序列号
     * @return com.ruoyi.aliyun.domain.CBLightDeviceInfo
     * @author FLInt
     * @date 2021/11/26 21:56
     */
//    private CBLightDeviceInfo getDeviceInfo(String deviceName) {
//        return CBLightDeviceMapper.selectDeviceInfo(deviceName);
//    }

    /**
     * 时间格式器
     */
    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 手动拍照，成功返回true
     *
     * @return java.lang.String
     * @author FLInt
     * @date 2021/10/20 13:12
     */
//    @Override
//    public String invokeTakePhoto(String deviceName) throws Exception {
//        InvokeThingServiceRequest invokeThingServiceRequest = new
//                InvokeThingServiceRequest()
//                .setIotInstanceId(getDeviceInfo(deviceName).getIotInstanceId())
//                .setProductKey(getDeviceInfo(deviceName).getProductKey())
//                .setDeviceName(deviceName)
//                .setArgs("{}")
//                .setIdentifier("capture");
//        InvokeThingServiceResponse response = aliyunClientService.creatClient().invokeThingService(invokeThingServiceRequest);
//        String jsonStr = com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response.body));
//        CallBackInfo callBackInfo = JSONObject.parseObject(jsonStr, CallBackInfo.class);
//        return callBackInfo.getSuccess().toString();
//    }
//
//    /**
//     * 查询历史图片，存储在服务器
//     *
//     * @author FLInt
//     * @date 2021/10/20 13:12
//     */
//    @Override
//    public Long queryDevicePhoto(String deviceName, Long startTime, Long endTime, int pageSize) throws Exception {
//        CBLightDeviceInfo deviceInfo = getDeviceInfo(deviceName);
//        if (deviceInfo != null) {
//            QueryDeviceEventDataRequest queryDeviceEventDataRequest = new
//                    QueryDeviceEventDataRequest()
//                    .setIotInstanceId(deviceInfo.getIotInstanceId())
//                    .setProductKey(deviceInfo.getProductKey())
//                    .setDeviceName(deviceName).setStartTime(startTime)
//                    .setEndTime(endTime).setPageSize(pageSize)
//                    .setIdentifier("uploadImageEvent").setEventType("info").setAsc(1);
//            QueryDeviceEventDataResponse response = aliyunClientService.creatClient().queryDeviceEventData(queryDeviceEventDataRequest);
//            String jsonStr = com.aliyun.teautil.Common.toJSONString(TeaModel.buildMap(response.body));
//            String dataStr = getJsonResult(jsonStr, "Data");
//            String jsonResult = getJsonResult(dataStr, "List");
//            EventInfo eventInfo = JSON.parseObject(jsonResult, EventInfo.class);
//            int i = insertPhotoInfo(eventInfo, deviceName, deviceInfo.getId());
//            PhotoData data = JSON.parseObject(dataStr, PhotoData.class);
//            if (data.getNextValid()) {
//                return data.getNextTime();
//            } else {
//                return Long.parseLong(Integer.toString(i));
//            }
//        } else {
//            return null;
//        }
//    }
//
//    @Override
//    public boolean downloadPhotoByUrl(String url, String dir, String fileName) {
//        return downloadImage(url, dir, fileName);
//    }
//
//    /**
//     * 将识别结果回调
//     * @author FLInt
//     * @date 2021/12/12 15:24
//     * @param responseBody django返回结果
//     * @param imgName 图片名字
//     * @param imgPath 图片路径
//     * @param deviceName 设备序列号
//     * @return java.lang.String
//     */
//    @Override
//    public String discernAndCallBack(String responseBody, String imgName, String imgPath, String deviceName) throws Exception {
//        CBLightDeviceInfo deviceInfo = getDeviceInfo(deviceName);
//        JSONArray jsonArray = JSON.parseArray(responseBody);
//        assert jsonArray != null;
//        System.out.println(jsonArray.getString(0));
//        discernEntity entity = JSONObject.parseObject(jsonArray.getString(0), discernEntity.class);
//        List<String> tagList = entity.getTag();
//        List<int[]> cornerList = entity.getCorner();
//        if (cornerList.size() == tagList.size()) {
//            CallBackDao callBackDao = new CallBackDao();
//            callBackDao.setImg_name(imgName);
//            // 转换坐标
//            // windows - \\profile , linux - /profile
//            List<float[]> corner = transformCorner(cornerList, imgPath.replace("/profile", profile));
//            List<TagAndCorner> tagAndCorners = new ArrayList<>();
//            for (int i = 0; i < tagList.size(); i++) {
//                TagAndCorner tagAndCorner = new TagAndCorner();
//                switch (tagList.get(i)) {
//                    case "hfs":
//                        tagAndCorner.setId("1");
//                        tagAndCorner.setName("褐飞虱");
//                        break;
//                    case "bbfs":
//                        tagAndCorner.setId("2");
//                        tagAndCorner.setName("白背飞虱");
//                        break;
//                    case "a1":
//                        tagAndCorner.setId("3");
//                        tagAndCorner.setName("蝼蛄");
//                        break;
//                    case "a2":
//                        tagAndCorner.setId("4");
//                        tagAndCorner.setName("二化螟");
//                        break;
//                    case "a3":
//                        tagAndCorner.setId("5");
//                        tagAndCorner.setName("铜绿丽金龟");
//                        break;
//                    case "a4":
//                        tagAndCorner.setId("6");
//                        tagAndCorner.setName("草地螟");
//                        break;
//                    case "a10":
//                        tagAndCorner.setId("7");
//                        tagAndCorner.setName("金黄镰翅野螟");
//                        break;
//                    case "a12":
//                        tagAndCorner.setId("8");
//                        tagAndCorner.setName("稻纵卷叶螟");
//                        break;
//                    case "a21":
//                        tagAndCorner.setId("9");
//                        tagAndCorner.setName("大螟");
//                        break;
//                    case "a102":
//                        tagAndCorner.setId("10");
//                        tagAndCorner.setName("棉铃虫");
//                        break;
//                    case "a122":
//                        tagAndCorner.setId("11");
//                        tagAndCorner.setName("粘虫");
//                        break;
//                    case "a22":
//                        tagAndCorner.setId("12");
//                        tagAndCorner.setName("玉米螟");
//                        break;
//                    case "a41":
//                        tagAndCorner.setId("13");
//                        tagAndCorner.setName("格蔗尺蛾");
//                        break;
//                    case "b13":
//                        tagAndCorner.setId("14");
//                        tagAndCorner.setName("灰胸突鳃金龟");
//                        break;
//                    case "b28":
//                        tagAndCorner.setId("15");
//                        tagAndCorner.setName("大黑鳃金龟");
//                        break;
//                    case "c21":
//                        tagAndCorner.setId("16");
//                        tagAndCorner.setName("黄足猎蝽");
//                        break;
//                    case "e12":
//                        tagAndCorner.setId("17");
//                        tagAndCorner.setName("烟青虫");
//                        break;
//                    case "e40":
//                        tagAndCorner.setId("18");
//                        tagAndCorner.setName("杨雪毒蛾");
//                        break;
//                    case "e90":
//                        tagAndCorner.setId("19");
//                        tagAndCorner.setName("榆黄足毒蛾");
//                        break;
//                    case "e120":
//                        tagAndCorner.setId("20");
//                        tagAndCorner.setName("橄榄绿尾尺蛾");
//                        break;
//                    case "g21":
//                        tagAndCorner.setId("21");
//                        tagAndCorner.setName("蟋蟀");
//                        break;
//                    default:
//                        tagAndCorner.setId("0");
//                        tagAndCorner.setName("未知目标");
//                        break;
//                }
//                tagAndCorner.setX(Float.toString(corner.get(i)[0]));
//                tagAndCorner.setY(Float.toString(corner.get(i)[1]));
//                tagAndCorner.setW(Float.toString(corner.get(i)[2]));
//                tagAndCorner.setH(Float.toString(corner.get(i)[3]));
//                tagAndCorners.add(tagAndCorner);
//            }
//            callBackDao.setFeature(tagAndCorners);
//            SimplePropertyPreFilter filter = new SimplePropertyPreFilter();
//            filter.getExcludes().add("params");
//            String jsonString = JSONObject.toJSONString(callBackDao, filter);
//            log.info("callBackArgs------->" + jsonString);
//            // 调用回调函数，将结果上传到阿里云服务器
//            InvokeThingServiceRequest invokeThingServiceRequest = new
//                    InvokeThingServiceRequest()
//                    .setIotInstanceId(deviceInfo.getIotInstanceId())
//                    .setProductKey(deviceInfo.getProductKey())
//                    .setDeviceName(deviceName).setArgs(jsonString).setIdentifier("discern");
//            InvokeThingServiceResponse serviceResponse =
//                    aliyunClientService.creatClient().invokeThingService(invokeThingServiceRequest);
//            String jsonStr = Common.toJSONString(TeaModel.buildMap(serviceResponse.body));
//            CallBackInfo callBackInfo = JSONObject.parseObject(jsonStr, CallBackInfo.class);
//            return callBackInfo.getSuccess().toString();
//        }
//        return "回调失败，请检查！";
//    }
//
    @Override
    public List<PhotoDao> selectPhotoList(SelectPhotoDao selectPhotoDao,Integer unitId) {
        if(selectPhotoDao.getEndTime()!=null) {
            Calendar now = Calendar.getInstance();
            now.setTime(selectPhotoDao.getEndTime());
            now.set(Calendar.DATE, now.get(Calendar.DATE) + 1);
            selectPhotoDao.setEndTime(now.getTime());
        }
//        int deviceId = selectPhotoDao.getDeviceId();
        String deviceName = selectPhotoDao.getDeviceName();
        List<PhotoDao> photoDaos = dataMapper.selectPhotoList(selectPhotoDao);
        //如果为管理员，默认不属于任何单位
        if(unitId == 0){
            return photoDaos;
        }else {
            SerDevicePermi selectDevice = new SerDevicePermi().setDeviceSerial(deviceName).setTypeId(1);
            int id = permiMapper.selectByDeviceSerialAndTypeId(selectDevice).getId();
            //获取虫情权限
            List<DevicePermiInsectInfo> insectPermiLst = permiMapper.selectInsectListByDeviceId(id);
            //用于存储权限虫子的编号
            List<String> retLst = new ArrayList<>();
            for (DevicePermiInsectInfo insectPermi : insectPermiLst) {
                String ret = insectPermi.getRet();
                if (!retLst.contains(ret)) {
                    retLst.add(ret);
                }
            }
            for(int i = 0;i< photoDaos.size();i++) {
                if (photoDaos.get(i).getTagForDraw() == null || photoDaos.get(i).getCorner() == null) {
                    continue;
                }
                String tagForDraw = photoDaos.get(i).getTagForDraw();
                String corner = photoDaos.get(i).getCorner();
                //用户独属的虫子信息
                List<String> tagListForUser = JSON.parseArray(tagForDraw, String.class);
//                List<String> tagListForUser = new ArrayList<>(tagList);
                // 将字符串数组转换为包含整数数组的列表
                ObjectMapper objectMapper = new ObjectMapper();
                try {
                    // 创建 TypeReference 以指定数组类型
                    List<int[]> cornerListForUser = objectMapper.readValue(corner, TypeFactory.defaultInstance().constructCollectionType(List.class, int[].class));
                    //在遍历tagList的过程中，记录需要删除的索引位置
                    List<Integer> indexesToRemove = new ArrayList<>();
                    for (int j = 0; j < tagListForUser.size(); j++) {
                        String tagValue = tagListForUser.get(j);
                        if (!retLst.contains(tagValue)) {
                            indexesToRemove.add(j);
                        }
                    }
                    //删除不需要的虫子信息
                    for (int k = indexesToRemove.size() - 1; k >= 0; k--) {
                        int indexToRemove = indexesToRemove.get(k);
                        tagListForUser.remove(indexToRemove);
                        cornerListForUser.remove(indexToRemove);
                    }
                    photoDaos.get(i).setCorner(JSON.toJSONString(cornerListForUser)).setTagManual(ParseString.getTagNum(JSON.toJSONString(tagListForUser))).setTagForDraw(JSON.toJSONString(tagListForUser));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
                return photoDaos;
        }
    }

    @Override
    public int deletePhoto(int id){
        return dataMapper.deleteTraplightPhoto(id);
    }

    @Override
    public SelectPhotoDao autoCountAgain(Integer id,Integer unitId){
        SelectPhotoDao photoDao = dataMapper.selectPhotoById(id);
        //设备序列号
        String deviceSerial = photoDao.getDeviceName();
        SerDevicePermi serDevicePermi = permiMapper.selectByDeviceSerial(deviceSerial);
        Integer deviceId = serDevicePermi.getId();
        String images = photoDao.getPhotoPath();
        String filename = photoDao.getPhotoName();
        String detectionImages = StringUtils.substringAfter(images, "profile");

        List<TraplightDetectionLog> detectionLogList = new ArrayList<>();
        ImgDrawCircleTool tool = new ImgDrawCircleTool();

        // 图片发送到Django进行识别
//        try {
//            ResponseEntity<String> responseEntity = Threads.detectionRequest(profile + detectionImages, detectionUrl);
//            log.info("responseEntity------->" + responseEntity.getBody());
//            // json格式的数据转换成数组格式
//            detectionLogList = JSON.parseArray(responseEntity.getBody(), TraplightDetectionLog.class);
//            //assert detectionLogList != null;
//            log.info("detection:" + detectionLogList.toString());
//        } catch (Exception e){
//            System.out.println(e.getMessage());
//        }
        // 图片调用远程rpc接口
        RpcRequest rpc = new RpcRequest("47.96.166.231", 10052, "siqing-files");
        try {
            String upload_oss_name = StringUtils.substringAfter(images, "profile/");
//            String res = rpc.getRpcRes(upload_oss_name);
            String res = Threads.rpcRequest(upload_oss_name, rpc::getRpcRes);
            log.info("responseEntity=======>"+res);
            detectionLogList = JSON.parseArray(res, TraplightDetectionLog.class);
            log.info(detectionLogList.toString());
        }catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            rpc.shutdownChannel();
        }

        SelectPhotoDao newPhotoDao = new SelectPhotoDao().setPhotoName(filename).setTagManual("").setCorner("").setTagForDraw("").setTagForUser("").setCornerForUser("")
                .setTag("").setResultPath("");
        if(!detectionLogList.isEmpty()) {
            for (TraplightDetectionLog detection : detectionLogList) {
                log.info(detection.toString());
                if (StringUtils.isNotEmpty(detection.getCorner())){
                    detection.setImagePath(images).setOriginalFileName(filename);
                    newPhotoDao.setTagForDraw(detection.getTag());
                    /*画框之后的结果图 resUrl  缩略图 已添加 */
                    List<String> tagList = JSON.parseArray(detection.getTag(), String.class);
                    if(unitId != 0){
                        //获取虫情权限
                        List<DevicePermiInsectInfo> insectPermiLst = permiMapper.selectInsectListByDeviceId(deviceId);
                        //用于存储权限虫子的编号
                        List<String> retLst = new ArrayList<>();
                        for (DevicePermiInsectInfo insectPermi : insectPermiLst) {
                            String ret = insectPermi.getRet();
                            if (!retLst.contains(ret)) {
                                retLst.add(ret);
                            }
                        }
                        //原始框信息
                        List<int[]> cornerList = detection.getCorner();
                        log.info("原始框信息1：" + JSON.toJSONString(detection.getCorner()));
                        //用户独属的框信息
                        List<int[]> cornerListForUser = new ArrayList<>(cornerList);
                        //用户独属的虫子信息
                        List<String> tagListForUser = new ArrayList<>(tagList);
                        //在遍历tagList的过程中，记录需要删除的索引位置
                        List<Integer> indexesToRemove = new ArrayList<>();
                        for (int i = 0; i < tagListForUser.size(); i++) {
                            String tagValue = tagListForUser.get(i);
                            if (!retLst.contains(tagValue)) {
                                indexesToRemove.add(i);
                            }
                        }
                        //删除不需要的虫子信息
                        for (int i = indexesToRemove.size() - 1; i >= 0; i--) {
                            int indexToRemove = indexesToRemove.get(i);
                            tagListForUser.remove(indexToRemove);
                            cornerListForUser.remove(indexToRemove);
                        }
                        log.info("tagForUser: " + tagListForUser + "\ncornerForUser:" + JSON.toJSONString(cornerListForUser));
                        if(tagListForUser.size() !=0 && cornerListForUser.size() !=0) {
                            newPhotoDao.setTagForUser(ParseString.getTagNum(JSON.toJSONString(tagListForUser))).setCornerForUser(JSON.toJSONString(cornerListForUser));
                            //绘制用户专属的结果图片
                            String resultPathForUser = tool.doDrawRectangleForUnit(unitId, cornerListForUser, tagListForUser, profile + detectionImages).replace(profile, Constants.RESOURCE_PREFIX);
                            log.info("用户的结果图的url：" + resultPathForUser);
                        }
                    }
                    String resultPath = tool.doDrawRectangleT(detection.getCorner(), tagList, profile + detectionImages).replace(profile, Constants.RESOURCE_PREFIX);
                    log.info("管理员结果图url:" + resultPath);
                    detection.setTag(ParseString.getTagNum(detection.getTag()));
                    detection.setStrCorner(JSON.toJSONString(detection.getCorner()));
                    newPhotoDao.setTag(detection.getTag()).setTagManual(detection.getTag()).setCorner(detection.getStrCorner())
                            .setPhotoName(detection.getOriginalFileName()).setResultPath(resultPath);
                    modelService.insertDetectionLog(detection);
                    log.info("成功识别到目标，结果已入库");
                } else {
                    newPhotoDao.setPhotoName(filename).setResultPath(images);
                    log.info("未识别到目标，开始识别下一张图片");
                }
                dataMapper.updatePhotoInfo(newPhotoDao);
                log.info(newPhotoDao.toString());
            }
            return newPhotoDao;
        }else {
            newPhotoDao.setPhotoName(filename).setResultPath(images);
            dataMapper.updatePhotoInfo(newPhotoDao);
            log.info("未识别到目标");
            return null;
        }



    }
//
//
//    /**
//     * 收到图片信息后，存到本地，上传数据库记录
//     *
//     * @param eventInfo  返回图片信息列表
//     * @param deviceName 设备序列号
//     * @return 总影响行数
//     * @author FLInt
//     * @date 2021/11/27 17:20
//     */
//    private int insertPhotoInfo(EventInfo eventInfo, String deviceName, String deviceId) {
//        int n = 0;
//        for (EventInfoValue infoValue : eventInfo.getEventInfo()) {
//            // 创建DAO
//            PhotoDao photoDao = new PhotoDao();
//            photoDao.setPhotoUpdateTime(SDF.format(new Date())).setDeviceId(deviceId).setDeviceName(deviceName)
//                    .setPhotoTime(SDF.format(new Date(Long.parseLong(infoValue.getTime()))));
//            // 去除斜杠
//            String outputData = infoValue.getOutputData().replaceAll("\\\\", "");
//            PhotoOutputData photoOutputData = JSON.parseObject(outputData, PhotoOutputData.class);
//            photoDao.setPhotoUrl(photoOutputData.getImgUrl());
//            // 下载图片
//            String path = "CBLightImg" + File.separator + deviceName;
//            String name = handleUrlToName(photoOutputData.getImgUrl()) + ".jpg";
//            photoDao.setPhotoName(name);
//            if (downloadImage(photoOutputData.getImgUrl(), profile + File.separator + path, name)) {
//                photoDao.setPhotoPath(File.separator + "profile" + File.separator + path + File.separator + name);
//            }
//            // 数据库
//            int i = CBLightDataMapper.insertPhotoInfo(photoDao);
//            n = n + i;
//        }
//        return n;
//    }

    /**
     * 转换坐标列表为字符串
     *
     * @param cornerList 坐标列表
     * @return java.lang.String
     * @author FLInt
     * @date 2021/12/2 16:48
     */
    private String transformString(List<int[]> cornerList) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < cornerList.size(); i++) {
            if (i == 0) {
                s.append(Arrays.toString(cornerList.get(i)));
            } else {
                s.append(", ").append(Arrays.toString(cornerList.get(i)));
            }
        }
        return s.toString();
    }

    /**
     * 将左下角、右上角坐标转换为左坐标、上坐标、宽、高站图片宽高的比值
     *
     * @param list    原坐标列表
     * @param imgPath 图片路径，用来解析图片宽高
     * @return 返回转换后的浮点值
     */
    private List<float[]> transformCorner(List<int[]> list, String imgPath) {
        List<float[]> cornerToRatio = new ArrayList<>();
        int[] widthAndHeight = geiImgWidthAndHeight(imgPath);
        for (int[] ints : list) {
            float[] floatTemp = new float[4];
            floatTemp[0] = ((float) ints[0] / (float) widthAndHeight[0]);
            floatTemp[1] = ((float) ints[3] / (float) widthAndHeight[1]);
            floatTemp[2] = (float) (ints[2] - ints[0]) / (float) widthAndHeight[0];
            floatTemp[3] = (float) (ints[3] - ints[1]) / (float) widthAndHeight[1];
            cornerToRatio.add(floatTemp);
        }
        return cornerToRatio;
    }

    /**
     * 获取图片像素大小
     *
     * @param imgPath 图片路径
     * @return int[]
     * @author FLInt
     * @date 2021/12/1 10:34
     */
    private int[] geiImgWidthAndHeight(String imgPath) {
        File file = new File(imgPath);
        BufferedImage bufferedImage = null;
        try {
            bufferedImage = ImageIO.read(file);
            return new int[]{bufferedImage.getWidth(), bufferedImage.getHeight()};
        } catch (Exception e) {
            e.printStackTrace();
            return new int[]{0, 0};
        }
    }

    /**
     * 通过URL下载图片
     *
     * @param url      图片链接
     * @param dir      保存目录
     * @param fileName 保存文件名
     * @return 保存图片状态
     */
    private boolean downloadImage(String url, String dir, String fileName) {
        boolean image = false;
        try {
            File localFile = getAbsoluteFile(dir, fileName);
            image = downloadImage(url, "JPEG", localFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * 获取文件，通过路径，没有文件就创建文件
     *
     * @param saveDir  保存路径
     * @param fileName 文件名
     * @return 返回文案类型
     * @throws IOException IO操作异常
     */
    private static File getAbsoluteFile(String saveDir, String fileName) throws IOException {
        File desc = new File(saveDir + File.separator + fileName);

        if (!desc.getParentFile().exists()) {
            if (!(desc.getParentFile().mkdirs())) {
                System.out.println("mkdir failed");
            }
        }
        if (!desc.exists()) {
            if (!(desc.createNewFile())) {
                System.out.println("create new file failed");
            }
        }
        return desc;
    }

    /**
     * JSON解析
     *
     * @param dataString json字符串
     * @param key        解析的key
     * @return java.lang.String
     * @author FLInt
     * @date 2021/11/27 14:06
     */
    private String getJsonResult(String dataString, String key) {
        JSONObject jsonObject = JSONObject.parseObject(dataString);
        return jsonObject.getJSONObject(key).toString();
    }

    /**
     * Url下载图片
     * 增加时间戳
     * BufferedImage subImage = read.getSubimage(0, 0, read.getWidth() - 110, read.getHeight());
     * isSuccess = ImageIO.write(subImage, formatName, localFile);
     *
     * @param imageUrl   Url地址
     * @param formatName 类型名
     * @param localFile  保存当地文件路径
     * @return 是否成功
     */
    private static boolean downloadImage(String imageUrl, String formatName, File localFile) {
        boolean isSuccess = false;
        URL url = null;
        try {
            url = new URL(imageUrl);
            BufferedImage read = ImageIO.read(url);
            Graphics2D graphics = read.createGraphics();
            /* 增加时间戳 */
            graphics.setColor(Color.BLACK);
            graphics.setFont(new Font("Time New Roman", Font.BOLD, 64));
            graphics.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
            graphics.drawString(handleUrlToName(imageUrl), 190, 100);
            isSuccess = ImageIO.write(read, formatName, localFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return isSuccess;
    }

    /**
     * 解析url为图片名字
     *
     * @param url 图片url
     * @return java.lang.String
     * @author FLInt
     * @date 2021/11/27 17:18
     */
    private static String handleUrlToName(String url) {
        StringBuilder builder = new StringBuilder(url);
        int i = builder.indexOf("?");
        if (i > 0) {
            builder.delete(i, builder.length());
        }
        int lastIndexOf = builder.lastIndexOf("/");
        builder.delete(0, lastIndexOf + 1);
        String s = builder.toString();
        String[] split = s.split("\\.");
        return split[0];
    }

    private static String addThum(String srcPath) {
        String res = "";
        if (StringUtils.isNotNull(srcPath)) {
            String[] str = new String[2];
            /* \\. 转义字符，相当于 . ,分隔出.前后的内容 */
            str = srcPath.split("\\.");
            res = str[0] + "__thum." + str[1];
        }
        return res;
    }
    private static String addUnit(String srcPath,Integer unitId) {
        String res = "";
        String[] str = new String[2];
        /* \\. 转义字符，相当于 . ,分隔出.前后的内容 */
        str = srcPath.split("\\.");
        res = str[0] + String.format("__%d.",unitId) + str[1];
        return res;
    }

}